package com.tang.script.variable;

import com.tang.script.exceptions.ScriptException;
import lombok.Setter;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Objects;

@Setter
public class VariableValueGetter {
    VariablesContainer variablesContainer;

    public Object getVariable(Constant constant, VariablesContainer variablesContainer) {
        if (Objects.isNull(variablesContainer)) throw new ScriptException("没有定义变量容器");

        if (variablesContainer.isForTitle()) {
            return constant.getTitle();
        }
//        Object value = variablesContainer.getValue(constant);
//        if (Objects.isNull(value)) {
//            return defaultValue(constant.getType(), variablesContainer);
//        }
        return resolveType(constant.getValue(), constant.getType(), variablesContainer);
//        return value;
    }

    private Object defaultValue(VariablesType type, VariablesContainer variablesContainer) {
        return type.getDefaultValue();
    }

    public Object getVariable(Variable variable, VariablesContainer variablesContainer) {
        if (Objects.isNull(variablesContainer)) throw new ScriptException("没有定义变量容器");

        Object value = variablesContainer.getValue(variable);
        if (value instanceof Collection) return value;
        if (Objects.isNull(value)) {
            return defaultValue(variable.getType(), variablesContainer);
        }
        return resolveType(value, variable.getType(), variablesContainer);
    }

    private Object resolveType(Object value, VariablesType variableType, VariablesContainer variablesContainer) {
        if (variableType == VariablesType.number) {
            try {
                return new BigDecimal(value + "");
            } catch (Exception e) {
                return defaultValue(variableType, variablesContainer);
            }
        }
        return value;
    }
}
